<template>
    <div class="container-body article-detail-body" :style="{ width: proxy.globalInfo.bodyWidth + 'px' }"
        v-if="Object.keys(articleInfo).length > 0">
        <!-- 板块信息 -->
        <div class="board-info">
            <router-link :to="`/forum/${articleInfo.pboardId}`" class="a-link">
                {{ articleInfo.boardName }}
            </router-link>
            <span class="iconfont icon-right" />
            <template v-if="articleInfo.boardId">
                <router-link :to="`/forum/${articleInfo.pboardId}${articleInfo.boardId}`" class="a-link">
                    {{ articleInfo.pboardName }}
                </router-link>
                <span class="iconfont icon-right" />
            </template>

            <span>{{ articleInfo.title }}</span>
        </div>
        <!-- 详情 -->
        <div class="detail-container" :style="{ width: proxy.globalInfo.bodyWidth - 120 + 'px' }">
            <div class="article-detail">
                <!-- 文章标题 -->
                <div class="article-title">
                    {{ articleInfo.title }}
                </div>
                <!-- 用户信息 -->
                <div class="user-info">
                    <Avatar :userId="articleInfo.userId" :width="50" />
                    <div class="user-info-detail">
                        <router-link :to="`/user/${articleInfo.userId}`" class="nick-name">{{ articleInfo.nickName
                            }}</router-link>
                        <div class="time-info">
                            <span class="span-info">{{ articleInfo.postTime }}</span>
                            <span class="span-info">{{ articleInfo.userIpAddress }}</span>
                            <span class="iconfont icon-eye-solid">
                                {{ articleInfo.readCount == 0 ? "阅读" : articleInfo.readCount }}
                            </span>
                        </div>
                    </div>
                </div>
                <!-- 文章内容 -->
                <div class="detail" id="detail" v-html="articleInfo.content"></div>
            </div>
            <!-- 附件 -->
            <div class="attachment-panel" v-if="attachment" id="view-attachment">
                <div class="attachment-title">附件</div>
                <div class="attachment-info">
                    <div class="iconfont icon-zip item" />
                    <div class="file-name item">{{ attachment.fileName }}</div>
                    <div class="size item">{{ proxy.Utils.sizeToStr(attachment.fileSize) }}</div>
                    <div class="item">需要<span class="integral">{{ attachment.integral }}</span>积分</div>
                    <div class="download-count item">已下载{{ attachment.downloadCount }}</div>
                    <div class="download-btn item">
                        <el-button type="primary" size="small"
                            @click="downloadAttachment(attachment.fileId)">下载</el-button>
                    </div>
                </div>
            </div>
            <!-- 评论 -->
            <div class="comment-panel" id="view-comment">
                <CommentList v-if="articleInfo.articleId" :articleId="articleInfo.articleId"
                    :articleUserId="articleInfo.userId" @updateCommentCount="updateCommentCount"></CommentList>
            </div>


        </div>
    </div>
    <!-- 快捷操作 -->
    <div class="quick-panel" :style="{ left: quickPanelLeft + 'px' }">
        <!-- 点赞 -->
        <el-badge :value="articleInfo.goodCount" type="info" :hidden="!articleInfo.goodCount > 0">
            <div class="quick-item" @click="haveLikeHandler">
                <span :class="['iconfont icon-good', haveLike ? 'have-like' : '']"></span>
            </div>
        </el-badge>
        <!-- 评论 -->
        <el-badge :value="articleInfo.commentCount" type="info" :hidden="!articleInfo.commentCount > 0">
            <div class="quick-item" @click="goToPosition('view-comment')">
                <span class="iconfont icon-comment"></span>
            </div>
        </el-badge>
        <!-- 附件 -->
        <div class="quick-item" @click="goToPosition('view-attachment')">
            <span class="iconfont icon-attachment"></span>
        </div>
        <!-- 图片预览 -->
        <ImageViewer ref="imageViewerRef" :imageList="previewImgList"></ImageViewer>
    </div>
</template>

<script setup>
import hljs from 'highlight.js';
import 'highlight.js/styles/atom-one-light.css';
import Avatar from '@/components/Avatar.vue'
import ImageViewer from '@/components/ImageViewer.vue';
import CommentList from './CommentList.vue';
import { ref, reactive, getCurrentInstance, onMounted, watch, nextTick } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useStore } from 'vuex';
const store = useStore();
const { proxy } = getCurrentInstance();
const router = useRouter();
const route = useRoute();

const api = {
    getArticleDetail: "/forum/getArticleDetail",
    doLike: "/forum/doLike",
    getUserDownloadInfo: "/forum/getUserDownloadInfo",
    attachmentDownload: "/api/forum/attachmentDownload",
}


const articleInfo = ref({})
const attachment = ref({})
const haveLike = ref(false)
// 获取文章详情
const getArticleDetail = async (articleId) => {
    let result = await proxy.Request({
        url: api.getArticleDetail,
        params: {
            articleId: articleId
        }
    });
    if (!result) {
        return;
    }
    articleInfo.value = result.data.forumArticleVO;
    attachment.value = result.data.attachmentVo;
    haveLike.value = result.data.haveLike
    store.commit("setCurrentPBoardId", result.data.forumArticleVO.pboardId)
    store.commit("setCurrentBoardId", result.data.forumArticleVO.boardId)
    // 图片预览
    imagePreview()
    //代码高亮
    highlightCode()
}

onMounted(() => {
    getArticleDetail(route.params.articleId)
})

//快捷操作
const quickPanelLeft = (window.innerWidth - proxy.globalInfo.bodyWidth) / 2 - 100
const goToPosition = (domId) => {
    document.querySelector("#" + domId).scrollIntoView();
}
//点赞
const haveLikeHandler = async () => {

    if (!store.getters.getLoginUserInfo) {
        store.commit("showLogin", true)
        return;
    }

    let result = await proxy.Request({
        url: api.doLike,
        params: {
            articleId: articleInfo.value.articleId
        }
    })
    if (!result) {
        return;
    }
    haveLike.value = !haveLike.value
    let goodCount = 1;
    if (!haveLike.value) {
        goodCount = -1;
    }

    articleInfo.value.goodCount = articleInfo.value.goodCount + goodCount
}

//附件下载
const downloadAttachment = async (fileId) => {
    const currentUserInfo = store.getters.getLoginUserInfo
    if (!currentUserInfo) {
        store.commit("showLogin", true)
        return;
    }

    //不需要积分
    if (attachment.value.integral == 0 || currentUserInfo.userId == articleInfo.value.userId) {
        downloadDo(fileId)
        return;
    }
    //获取用户积分
    let result = await proxy.Request({
        url: api.getUserDownloadInfo,
        params: {
            fileId: fileId
        }
    })
    if (!result) {
        return;
    }
    //判断是否已经下载过
    if (result.data.haveDownload) {
        downloadDo(fileId)
        return;
    }
    //判断积分是否足够
    if (result.data.userIntegral < attachment.value.integral) {
        proxy.Message.warning("积分不足，请先充值")
        return;
    }

    proxy.Confirm(`你还有${result.data.userIntegral}积分，下载扣除${attachment.value.integral}积分，是否继续下载？`, () => {
        downloadDo(fileId)
    })
}
const downloadDo = (fileId) => {
    document.location.href = api.attachmentDownload + "?fileId=" + fileId;
    attachment.value.downloadCount = attachment.value.downloadCount + 1
}

//图片预览
const imageViewerRef = ref(null)
const previewImgList = ref([])
const imagePreview = () => {
    nextTick(() => {
        const imageNodeList = document.querySelector("#detail").querySelectorAll("img")
        const imageList = []
        imageNodeList.forEach((item, index) => {
            const src = item.getAttribute("src")
            imageList.push(src)
            item.addEventListener("click", () => {
                imageViewerRef.value.show(index)
            })
        })
        previewImgList.value = imageList
    })
}

//代码高亮
const highlightCode = () => {
    nextTick(() => {
        let blocks = document.querySelectorAll("pre code");
        blocks.forEach((item) => {
            hljs.highlightBlock(item);
        });
    })
}
//更新评论数量
const updateCommentCount = (commentCount) => {
    articleInfo.value.commentCount = commentCount
}

</script>

<style lang="scss">
.article-detail-body {
    .board-info {
        line-height: 30px;
        font-size: 14px;

        .icon-right {
            margin: 0 10px;
        }
    }

    .detail-container {
        .article-detail {
            background: #fff;
            padding: 15px;

            .article-title {
                font-weight: bold;
            }

            .user-info {
                display: flex;
                align-items: center;
                gap: 16px; // 调整元素之间的间距
                margin-top: 10px;
                margin-bottom: 10px;
                padding-bottom: 15px;
                border-bottom: 1px solid #ddd;

                .avatar {
                    border-radius: 50%;
                    overflow: hidden;
                }

                .user-info-detail {
                    display: flex;
                    flex-direction: column;

                    .nick-name {
                        font-size: 15px;
                        color: #8d8d8d;
                        text-decoration: none;

                        &:hover {
                            color: var(--link);
                        }
                    }

                    .time-info {
                        font-size: 12px;
                        color: var(--text);
                        display: flex;
                        align-items: center;
                        margin-top: 5px;

                        .iconfont {
                            font-size: 14px;
                        }

                        .iconfont::before {
                            padding-right: 3px;
                        }

                        .span-info {
                            margin-right: 10px;
                        }
                    }
                }
            }

            .detail {
                // margin-top: 10px;
                letter-spacing: 1px;
                line-height: 20px;

                a {
                    text-decoration: none;
                    color: var(--link);
                }

                img {
                    max-width: 90%;
                    cursor: pointer;
                }

                p {
                    padding: 10px 0;
                }
            }



        }

        .attachment-panel {
            margin-top: 20px;
            background: #fff;
            padding: 20px;

            .attachment-title {
                font-size: 16px;
            }

            .attachment-info {
                display: flex;
                align-items: center;
                color: #9f9f9f;
                margin-top: 10px;
            }

            .item {
                margin-right: 10px;
            }

            .icon-zip {
                font-size: 20xp;
                color: #6ca1f7;
            }

            .file-name {
                color: #6ca1f7;
            }

            .integral {
                color: red;
                padding: 0 5px;
            }
        }

        .comment-panel {
            margin-top: 20px;
            background: #fff;
            padding: 20px;
        }


    }
}

.quick-panel {
    position: fixed;
    width: 50px;
    top: 200px;
    text-align: center;

    .el-badge__content.is-fixed {
        top: 3px;
        right: 12px;
    }

    .quick-item {
        width: 45px;
        height: 45px;
        display: flex;
        justify-content: center;
        align-items: center;
        border-radius: 50%;
        background: #fff;
        margin-bottom: 20px;
        cursor: pointer;

        .iconfont {
            font-size: 22px;
            color: var(--text);
        }

        .have-like {
            color: pink
        }
    }
}
</style>